package tgc.edu.yzy.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.yzy.custom.Custom;
import tgc.edu.yzy.entity.EimAdmin;
import tgc.edu.yzy.entity.EimAdministrator;
import tgc.edu.yzy.entity.EimRegister;
import tgc.edu.yzy.entity.EimUser;
import tgc.edu.yzy.entity.Record;
import tgc.edu.yzy.repostory.EimRegisterRepository;
import tgc.edu.yzy.security.User2;
import tgc.edu.yzy.service.AdminService;
import tgc.edu.yzy.service.AdministatorService;
import tgc.edu.yzy.service.InvoiceService;
import tgc.edu.yzy.service.MailServiceImpl;
import tgc.edu.yzy.service.RecordService;
import tgc.edu.yzy.service.UserService;

@Controller
public class LoginController {
	@Autowired
	private AdminService admin;
	@Autowired
	private AdministatorService admini;
	@Autowired
	private UserService userservice;
	@Autowired
	private RecordService recordservice;
	@Autowired
	private Custom custom;
	@Autowired
	private EimRegisterRepository userDAO; 
	@Autowired
	private InvoiceService invo;
	/***
	 * 首页
	 * @return
	 */
	@RequestMapping(value="/login")
	public String login() {
		return "login";
	}
	/***
	 * 登陆成功跳转得到这里
	 * @param map
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/")
	public String index(ModelMap map,HttpServletRequest request,HttpSession session){
		custom.startrecord(request);
		session.removeAttribute("yzm");
		return "redirect:home";
	}
	/***
	 * 跳转成功以后访问到这里，然后防止刷新，跳转到home 给页面参数
	 * @param map
	 * @return
	 */
	@RequestMapping(value="home")
	public String home(ModelMap map) {
		Integer user2 = custom.getUser2();
		Optional<EimRegister> optional = userDAO.findById(user2);
		EimRegister eim =null;
		if(optional.isPresent()) {
			 eim= optional.get();
		}
		Date maxdate = eim.getMaxdate();
		Date time=new Date();
		long diff = maxdate.getTime() - time.getTime();
		long diffDays = diff / (24 * 60 * 60 * 1000)+1;
		
		EimUser eimusers = userservice.findById(user2);
		System.out.println(eimusers);
		if(eimusers!=null) {
			if("1".equals(eimusers.getQl())) {
				map.put("guanli", "ok");
			}
		}
		map.put("timea", diffDays);
		return "home/home";
	}
	/***
	 * 注销登录
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/over")
	public String logout(HttpServletRequest request) {
		custom.endrecord(request);
		return "redirect:logout";
	}
	/***
	 * 同登录一样 防止用户刷新
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/console")
	public String console(ModelMap map) {
		EimAdministrator s=admini.findById(custom.getUser2());
		if(s!=null) {
			//旗下总租户
			long adminqwe=admin.count();
			map.put("admincon", adminqwe);
			
			//旗下总用户
			long adminiqwe=admini.count();//系统管理员用户
			long repo=userDAO.count();//
			long uu=repo-adminiqwe;
			map.put("uu", uu);
			
			//总报销发票的数量
			long inuu=invo.count();
			map.put("inuu", inuu);
			//用户数量
			long ad=uu-adminqwe;
			map.put("as", ad);
		}
		return "home/views/console";
	}
	/***
	 * 跳转到租户管理员操作
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/users")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public String users(ModelMap map) {
		return "home/views/users";
	}
	/***
	 * 跳转到查看新增用户记录的页面
	 * @return
	 */
	@RequestMapping(value="/trading")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public String trading() {
		return "home/views/trading";
	}
	/***
	 * 跳转到日志表
	 * @return
	 */
	@RequestMapping(value="/record")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public String record() {
		return "home/views/record";
	}
	/***
	 * 修改密码 时 查询原密码是否正确
	 * @param password
	 * @return
	 */
	@RequestMapping(value="pwd")
	@ResponseBody
	private Boolean password(String password) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		boolean f = encoder.matches(password,custom.getUserpassword());
		return f;
	}
	/***
	 * 修改密码
	 * @param request
	 * @param password3
	 * @return
	 */
	@RequestMapping(value="editpassword")
	public String editpassword(HttpServletRequest request,String password3) {
		Optional<EimRegister> optional = userDAO.findById(custom.getUser2());
		if(optional.isPresent()) {
			optional.get();
		}
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		optional.get().setPassword(encoder.encode(password3));
		userDAO.save(optional.get());
		String operation="修改密码";
		String content=optional.get().getName()+"修改了密码";
		custom.record(request, operation, content);
		return "redirect:over";
	}
	/***
	 * 发送邮件
	 * @param emil
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/amil")
	@ResponseBody
	private Object amil(String emil,HttpSession session) {
		custom.securitycode(emil, session);
		return "OK";
	}
	/***
	 * 查询是否存在这个用户
	 * @param usern
	 * @return
	 */
	@RequestMapping(value="usern")
	@ResponseBody
	private Boolean usern(String usern) {
		EimRegister usernamess = userDAO.findByUsername(usern);
		if(usernamess==null) {
			return true;
		}else {
			return false;
		}
		
	}
}
